const mfs = require('./mfs');
const utils = require('./utils');
const ccc = require('./ccc');
const and = require('./android');

// step 1 读取路径
let i = 2;
let packPath = "";
while (i < process.argv.length) {
    var arg = process.argv[i];
    switch (arg) {
        case '--path':
        case '-p':
            packPath = process.argv[i + 1];
            i += 2;
            break;
        default:
            i++;
            break;
    }
}

// step 2 读取配置
const configPath = mfs.join(packPath, 'config.json');
const backPath = mfs.join(packPath, 'back.json');
if (!mfs.exists(configPath)) {
    console.log('没有找到配置文件');
    return;
}
const config = require(configPath);
let backConfig;
if (!mfs.exists(backPath)) {
    backConfig = {
        clientVer: '0',
        appCode: 0
    };
} else {
    backConfig = require(backPath);
}

const projectPath = mfs.join(packPath, '..', '..');
const buildPath = mfs.join(projectPath, 'build', 'jsb-link');
// 调用打包
if (utils.isMac()) {
    config.enginePath = '/Applications/CocosCreator/Creator/' + config.engineVer + '/CocosCreator.app/Contents';
} else {
    config.enginePath = 'C:/CocosDashboard/resources/.editors/Creator/' + config.engineVer;
}

// step3 判断是否构建
if (utils.compareVersion(config.clientVer, backConfig.clientVer || '0')) {
    console.log('Coocs开始构建');
    config.path = projectPath;
    ccc.pack(config).then(() => {
        console.log('Cocos构建成功');
        hotupdate();
    }).catch(() => {
        console.log('Cocos构建失败');
    });
} else {
    pack();
}

// step4 热更制作
function hotupdate() {
    const dirName = 'v' + config.clientVer.replace(/\./g, '_');
    // 将未加密的文件保存
    const backPath = mfs.join(buildPath, 'js backups (useful for debugging)');
    let toBackDir = '';
    if (utils.isMac()) {
        toBackDir = '/User';
    } else if (utils.isWindows()) {
        toBackDir = 'D:'
    }

    const toPath = mfs.join(toBackDir, 'pack', 'jsBack', config.title, dirName);// 这个路径自定义
    console.log('备份加密文件', backPath + '到' + toPath);
    mfs.cp(backPath, toPath);
    if (!config.debug) { // 如果是打包测试，则无需热更
        // 复制文件到当前文件夹
        const src = mfs.join(buildPath, 'src');
        const res = mfs.join(buildPath, 'res');
        const subpackages = mfs.join(buildPath, 'subpackages');
        const dirPath = mfs.join(packPath, dirName);
        mfs.cp(src, mfs.join(dirPath, 'src'));
        mfs.cp(res, mfs.join(dirPath, 'res'));
        mfs.cp(subpackages, mfs.join(dirPath, 'subpackages'));
        console.log('热更文件打包');
        const info = ccc.generator({
            dirPath: dirPath,
            version: config.clientVer
        });
        // 将manifest的信息写入build目录，打包时保持最新的manifest
        const destManifest = mfs.join(buildPath, info.path);
        mfs.writeFile(destManifest, JSON.stringify(info.manifest, null, 0));

        // 上传到cos
        const cosPath = '/app/' + config.title + '/hotupte/' + dirName;
        const cmd = 'coscmd upload -r ' + dirPath + ' ' + cosPath;
        utils.runSh(cmd).then(() => {
            console.log('上传成功');
            backConfig.clientVer = config.clientVer;
            pack();
        }).catch(() => {
            console.log('上传cos失败');
        });

    } else {
        pack();
    }
}

// step5 打包
function pack() {
    if (config.appCode > backConfig.appCode || 0) {
        // 打包安卓
        console.log('执行Android打包');
        config.androidPath = mfs.join(buildPath, 'frameworks', 'runtime-src', 'proj.android-studio');
        config.buildToolsVersion = '28.0.3';
        let outDir = '';
        if (utils.isMac()) {
            outDir = '/User';
        } else if (utils.isWindows()) {
            outDir = 'D:'
        }
        config.outDir = mfs.join(outDir, 'pack');// 这个路径自定义

        // 之所以将签名文件放到这里，比较安全
        config.storeFile = mfs.join(outDir, 'key', '你的密钥文件');
        config.storePassword = '签名密钥';
        config.keyAlias = '签名别称';
        config.keyPassword = '别称密钥';
        and.pack(config).then(() => {
            console.log('Android打包成功');
            backConfig.appCode = config.appCode;
            saveConfig();
        }).catch(() => {
            console.log('Android打包失败');
        });
    } else {
        saveConfig();
    }
}

function saveConfig() {
    console.log('写入记录');
    mfs.writeFile(backPath, JSON.stringify(backConfig));
    console.log('写入备份成功');
}